import { ref, reactive } from 'vue';
import { smartSentry } from '/@/lib/smart-sentry';
import { message, Modal } from 'ant-design-vue';
import { SmartLoading } from '/@/components/framework/smart-loading';

const queryFormState = {
  pageNum: 1,
  pageSize: 10,
};

export function PageMixin() {
  // 查询表单form
  const queryForm = reactive({ ...queryFormState });
  // 总数
  const total = ref(0);
  // 表格加载loading
  const tableLoading = ref(false);
  // 表格数据
  const tableData = ref([]);
  // 选择表格行
  const selectedRowKeyList = ref([]);
  // 重置查询条件
  function resetQueryForm(defalutData = {}) {
    let pageSize = queryForm.pageSize;
    Object.assign(queryForm, queryFormState, defalutData);
    queryForm.pageSize = pageSize;
    // queryData();
  }
  // 表格请求
  async function queryTableData(api) {
    tableLoading.value = true;
    try {
      let queryResult = await api(queryForm);
      tableData.value = queryResult.data.list;
      total.value = queryResult.data.total;
    } catch (e) {
      smartSentry.captureError(e);
    } finally {
      tableLoading.value = false;
    }
  }
  // 确认删除
  function deleteFn(data, api, keyId) {
    return new Promise((r) => {
      Modal.confirm({
        title: '提示',
        content: '确定要删除选吗?',
        okText: '删除',
        okType: 'danger',
        onOk() {
          SmartLoading.show();
          try {
            api(data[keyId]).then(() => {
              message.success('删除成功');
              // queryData();
            })
          } catch (e) {
            smartSentry.captureError(e);
          } finally {
            SmartLoading.hide();
            r()
          }
        },
        cancelText: '取消',
        onCancel() { },
      });
    })
  }
  function batchDeleteFn(api) {
    return Promise((r) => {
      Modal.confirm({
        title: '提示',
        content: '确定要批量删除这些数据吗?',
        okText: '删除',
        okType: 'danger',
        onOk() {
          try {
            SmartLoading.show();
            api(selectedRowKeyList.value).then(() => {
              message.success('删除成功');
            });
          } catch (e) {
            smartSentry.captureError(e);
          } finally {
            SmartLoading.hide();
            r()
          }
        },
        cancelText: '取消',
        onCancel() { },
      });
    })
  }

  return {
    queryForm,
    total,
    tableLoading,
    tableData,
    selectedRowKeyList,
    resetQueryForm,
    queryTableData,
    deleteFn,
    batchDeleteFn,
  };
}